package com.purong.purong.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.purong.purong.R;
import com.purong.purong.util.CommonUtil;

/**
 * Created by zengwenjie on 2017/11/20.
 */
public class CustomText extends LinearLayout {
    private Context mContext;
    private String content;
    private int maxLength=8;
    private int color;
    private int size;
    public CustomText(Context context) {
        super(context);
        this.mContext=context;
    }

    public CustomText(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext=context;
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.justify_textview);
        color = ta.getResourceId(R.styleable.justify_textview_text_color, 0);
        maxLength=ta.getInteger(R.styleable.justify_textview_text_length, 4);
        size=ta.getInteger(R.styleable.justify_textview_text_size,14);
        content=ta.getString(R.styleable.justify_textview_text_content);
        ta.recycle();
        if (context!=null)
        initView();
    }

    public CustomText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    public void setText(String s){
        this.content=s;
        initView();
    }
    private void initView(){
        removeAllViews();
        LayoutInflater mInflater = LayoutInflater.from(mContext);
        View myView = mInflater.inflate(R.layout.custom_text_lay, null);
        addView(myView);
        LinearLayout layout=(LinearLayout) myView.findViewById(R.id.main_lay);
        layout.setLayoutParams(new LinearLayout.LayoutParams(CommonUtil.dip2px(mContext,size*maxLength),LinearLayout.LayoutParams.WRAP_CONTENT));
        if (content==null)
            return;
        TextView tv;
        TextView empty;
        char[] chars=content.toCharArray();
        for (int i = 0; i <chars.length; i++) {
            tv=new TextView(mContext);
            tv.setTextSize(size);
            if (color!=0){
                tv.setTextColor(mContext.getResources().getColor(color));
            }else {
                tv.setTextColor(Color.parseColor("#000000"));
            }

            tv.setText(String.valueOf(chars[i]));
            layout.addView(tv);
            if (i!=chars.length-1){
                empty=new TextView(mContext);
                empty.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT,1));
                layout.addView(empty);
            }

        }
    }
}
